import { getToken, setToken, removeToken } from "@/utils/auth";
import { loginAPI, userInfoAPI, logoutAPI } from "@/api/userAccount";
import { resetRouter } from "@/router";
import { Message } from "element-ui";

const stateGlobal = {
    token: getToken(),
    hasUserInfo: false,
    nickname: "",
    avatar: "",
    introduction: "",
    roles: [],
    userInfo: {},
};

const mutations = {
    SET_HAS_USER_INFO: (state, hasUserInfo) => {
        state.hasUserInfo = hasUserInfo;
    },
    SET_TOKEN: (state, token) => {
        state.token = token;
    },
    SET_NAME: (state, nickname) => {
        state.nickname = nickname;
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles;
    },
    SAVE_USERINFO: (state, userInfo) => {
        state.userInfo = userInfo;
    },
};

const actions = {
    // user login
    async loginAction({ commit }, loginForm) {
        try {
            const { code, data, message } = await loginAPI(loginForm);
            if (code !== 200) {
                Message.error(message);
                return false;
            }
            commit("SET_TOKEN", data);
            setToken(data);
            return true;
        } catch (error) {
            Message.error("网络错误,登录失败");
            return false;
        }
    },
    // get userInfo
    async userInfoAction({ commit }) {
        try {
            const { code, data: userInfo, message } = await userInfoAPI();
            if (code !== 200) {
                Message.error(message);
                return false;
            }
            // userInfo.roles = [{ name: "九条米法" }];
            const { nickname, avatar, roles } = userInfo;
            commit("SET_NAME", nickname);
            commit("SET_AVATAR", avatar);
            commit("SET_ROLES", roles);
            commit("SET_HAS_USER_INFO", true);
            commit("SAVE_USERINFO", userInfo);
            return userInfo;
        } catch (error) {
            Message.error("网络错误,获取用户信息失败");
        }
    },
    // logout
    async logout({ commit }) {
        try {
            await logoutAPI();
        } finally {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_HAS_USER_INFO", false);
            removeToken();
            resetRouter();
        }
    },
};

export default {
    namespaced: true,
    state: stateGlobal,
    mutations,
    actions,
};
